var scene, camera, renderer;
var allTexture;
var ASSETSURL = "../assets/07/"; // 资源主目录路径
var mixer = null;
var clock = new THREE.Clock();
var animations = [];
var role = null;
var actionState = "";
var nextRX = 0,
  nextRY = 0;

// 初始化
function init() {
  scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(0x040455, 0.003);
  createCamera();

  renderer = new THREE.WebGLRenderer({
    antialias: true,
  });
  renderer.setSize(document.body.clientWidth, document.body.clientHeight);
  renderer.setClearColor(new THREE.Color(0xcce7f5));
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  document.getElementById("container").appendChild(renderer.domElement);

  new THREE.OrbitControls(camera, renderer.domElement);
  addLight();
  createStage();
  loadModel();
  loop();
}

// 创建相机
function createCamera() {
  camera = new THREE.PerspectiveCamera(
    90,
    document.body.clientWidth / document.body.clientHeight,
    0.1,
    1000
  );
  camera.position.set(0, 0.8, 1);
}

// 创建地面
function createStage() {
  var plane_map = new THREE.TextureLoader().load(ASSETSURL + "imgs/grass.jpg");
  plane_map.wrapS = THREE.RepeatWrapping;
  plane_map.wrapT = THREE.RepeatWrapping;
  plane_map.repeat.set(10, 10);
  var mesh = new THREE.MeshPhysicalMaterial({
    map: plane_map,
    side: THREE.DoubleSide,
  });
  mesh.reflectivity = 0;
  mesh.clearCoatRoughness = 1;
  mesh.metalness = 0.2;

  var plane = new THREE.Mesh(new THREE.BoxBufferGeometry(5, 5, 0.2), mesh);
  plane.receiveShadow = true;
  plane.position.set(0, -0.1, 0);
  plane.rotation.x = 0.5 * Math.PI;

  scene.add(plane);
}

// 加载模型
function loadModel() {
  var loader = new THREE.GLTFLoader();
  loader.load(ASSETSURL + "model/scene.gltf", function (gltf) {
    role = gltf.scene;
    role.scale.set(0.001, 0.001, 0.001);
    role.position.set(0, 0.3, 0);
    mixer = new THREE.AnimationMixer(role);
    animations = gltf.animations;
    // console.log(animations);
    var tween = new TweenMax(role.position, 1.7, {
      y: 0.38,
      repeat: -1,
      yoyo: true,
      yoyoEase: true,
    });
    actionAnimation(1);
    scene.add(role);
  });
}

function actionAnimation(index) {
  actionState = animations[index].name;
  mixer.clipAction(animations[index]).play();
}

function addShadow(obj) {
  for (var i = 0; i < obj.children.length; i++) {
    var item = obj.children[i];
    item.castShadow = true;
    item.receiveShadow = true;
    if (item.children) {
      addShadow(item);
    }
  }
}

// 添加灯光
function addLight() {
  var ambientLight = new THREE.AmbientLight(0xc2c2c2);
  ambientLight.intensity = 0.5;
  scene.add(ambientLight);

  var frontDirLight = new THREE.DirectionalLight(0xffffff);
  frontDirLight.position.x = 0;
  frontDirLight.position.y = 0.6;
  frontDirLight.position.z = 2;
  frontDirLight.intensity = 1;
  frontDirLight.castShadow = true;
  frontDirLight.shadow.mapSize.set(2048, 2048);
  scene.add(frontDirLight);
  //   var helper = new THREE.DirectionalLightHelper(frontDirLight)
  //   scene.add(helper)

  var frontDirLight2 = new THREE.DirectionalLight(0xffffff);
  frontDirLight2.position.x = 0;
  frontDirLight2.position.y = 6;
  frontDirLight2.position.z = 0;
  frontDirLight2.intensity = 0.5;
  frontDirLight2.castShadow = true;
  frontDirLight2.shadow.mapSize.set(2048, 2048);
  scene.add(frontDirLight2);
}

// 主循环
function loop() {
  requestAnimationFrame(loop);

  var delta = clock.getDelta();
  if (mixer) mixer.update(delta);
  renderer.render(scene, camera);
  camera.lookAt(scene.position);
  if (role) {
    role.rotation.x += (nextRX - role.rotation.x)/5;
    role.rotation.y += (nextRY - role.rotation.y)/5;
  }
  // console.log(camera.position);
}

window.addEventListener(
  "resize",
  function () {
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();
    renderer.setSize(document.body.clientWidth, document.body.clientHeight);
  },
  false
);

var tracker = new tracking.LandmarksTracker();

var video = document.getElementById("video");
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
tracker.setInitialScale(4);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.1);

tracking.track("#video", tracker, { camera: true });

tracker.on("track", function (event) {
  context.clearRect(0, 0, canvas.width, canvas.height);
  if (!event.data) return;
  event.data.faces.forEach(function (rect) {
    context.strokeStyle = "#a64ceb";
    context.strokeRect(rect.x, rect.y, rect.width, rect.height);
    context.font = "11px Helvetica";
    context.fillStyle = "#fff";
    context.fillText(
      "x: " + rect.x + "px",
      rect.x + rect.width + 5,
      rect.y + 11
    );
    context.fillText(
      "y: " + rect.y + "px",
      rect.x + rect.width + 5,
      rect.y + 22
    );
    nextRY = 0.1 - rect.y / 320;
    nextRX = 0.1 - rect.x / 240;
  });

  event.data.landmarks.forEach(function (landmarks) {
    for (var l in landmarks) {
      context.beginPath();
      context.fillStyle = "#04f";
      context.arc(landmarks[l][0], landmarks[l][1], 2, 0, 2 * Math.PI);
      context.fill();
    }
  });
});


window.onload = init;
